import React, { memo, useEffect, useRef, useState } from 'react';
import {
  ConfigProvider,
  Table,
  Modal,
  Button,
  Form,
  Input,
  Popconfirm,
  Space,
  Dropdown,
  message,
  Drawer,
  Menu,
  Descriptions,
  Tag,
  Select
} from 'antd';
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  MinusCircleOutlined
} from '@ant-design/icons';
import DivWrapper from './style';
import zhCN from 'antd/es/locale/zh_CN';
import http from '@/services/request';
import store from '@/pages/home/store';
import { SearchSelector, DataType } from './config';
import { action3, action4 } from '@/pages/home/createAction';

//form
const NewForm = (props: any) => {
  return (
    <Form ref={props.newref}>
      <Form.Item
        label="产品名称"
        name="productName"
        rules={[{ required: true, message: '请输入产品名称' }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        label="产品等级"
        name="grade"
        rules={[{ required: true }]}
      >
        <Select
          defaultValue="B"
          style={{ width: 120 }}
          options={[
            { value: 'A', label: '优质' },
            { value: 'B', label: '普通' },
            { value: 'C', label: '劣质 ' },
          ]}
        />
      </Form.Item>
      <Form.Item
        label="仓库名称"
        name="repoType"
        rules={[{ required: true, message: '请输入仓库名称' }]}
      >
        <Input />
      </Form.Item>
    </Form>
  );
};
//按钮组
const Buttongroup = (props: any) => {
  return (
    <div style={{ marginBottom: 10, float: 'left' }}>
      <Button
        type="primary"
        onClick={() => props.add()}
        style={{ marginRight: 10 }}
      >
        新增数据
      </Button>
      <Button
        danger
        onClick={() => {
          props.checkIt();
        }}
        style={{ marginRight: 10 }}
      >
        批量删除
      </Button>
    </div>
  );
};
const product = memo(() => {
  //更多功能定位id
  const [Drawerid, setDrawerid]: any = useState({});
  //抽屉开关
  const [DrawerVisible, setDrawerVisible] = useState(false);
  //复选框批量删除
  const [itemSelected, setItemSelected] = useState<React.Key[]>([]);
  //是否新增
  const [edited, setedited]: any = useState();
  //高级检索
  const newref: any = useRef();
  const [dataSource, setdataSource]: any = useState([]);
  useEffect(() => {
    http.get('/server/productionSlaughter/list/1/10').then((res) => {
      setdataSource(res.data.records);
    });
  }, []);
  //复选框的逻辑
  const selectionType = 'checkbox';
  //复选框的内容设定
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      let res: any[] = [];
      selectedRows.map((i) => res.push(i.id));
      setItemSelected(res);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name
    })
  };

  //批量删除
  const checkIt = () => {
    http({
      url: `/server/productionSlaughter/deletion/batch`,
      method: 'delete',
      data: JSON.stringify(itemSelected),
      headers: { 'Content-Type': 'application/json' }
    }).then((res) => {
      http.get('/server/productionSlaughter/list/1/10').then((res) => {
        setdataSource(res.data.records);
      });
    });
  };
  // 控制对话框显示（新增）
  const [addModalVisible, setAddModalVisible] = useState(false);
  // 对话框确认
  const handleAddModalOk = () => {
    setAddModalVisible(false);
    //如果id存在--就是修改
    if (store.getState().name === '编辑') {
      const newedited = newref.current.getFieldsValue();
      http
        .put(`/server/productionSlaughter/update/${edited}`, {
          ...newedited
        })
        .then((res) => {
          http
            .get('/server/productionSlaughter/list/1/10')
            .then((res) => setdataSource(res.data.records));
        });

      return;
    }

    //id不在--就是新增
    else {
      const measurement = newref.current.getFieldsValue();
      const { grade, productName, userId } = measurement;
      let newdata = {
        grade,
        productName,
        userId,
        deleted: false
      };
      http
        .post('/server/productionSlaughter/save', newdata)
        .then((res: any) => {
          if (res.statusCode === 20000) {
            setdataSource([...dataSource, newdata]);
          } else {
            message.error(res.message);
          }
        });
    }
    setAddModalVisible(false);
  };
  //编辑
  const edit = (id: any) => {
    setAddModalVisible(true);

    //这里必须单单setField..会报错："表单还没挂载调用了setFieldsValue",应该用异步，设一个定时器
    setTimeout(() => {
      newref.current.setFieldsValue({
        ...id
      });
      store.dispatch(action3('编辑'));
      setedited(id.id);
    }, 0);
  };
  // 对话框取消
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };
  const add = () => {
    store.dispatch(action4('新增'));
    setTimeout(() => {
      setTimeout(() => {
        newref.current.setFieldsValue({
          grade: '',
          productName: '',
          userId: ''
        });
      }, 0);
    });
    setAddModalVisible(true);
  };
  const indexTable = {
    pagination: {
      //每页3条项目
      defaultPageSize: 10,
      //自定义每页显示数目
      showSizeChanger: true,
      //当前的页数和大小
      onShowSizeChange: (current: any, pageSize: any) => {},
      //自定义每页显示项目的选项
      pageSizeOptions: ['5', '10', '15'],

      // 输入指定页码跳页
      showQuickJumper: true,
      //跳页之后的回调函数
      onShowQuickJump: (page: any) => {},
      //全部项目数（最好可以用变量表示，与实际项目数关联）
      total: dataSource?.length,
      // 改变的回调函数
      onChange: (page: any) => {}
    }
  };
  //table的数据名
  const FormColumns: any = [
    {
      title: '产品等级',
      dataIndex: 'grade',
      key: 'grade',
      width: 150,
      render: (text) => {
        if (text === 'A') {
          return (
            <Tag icon={<CheckCircleOutlined />} color="success">
              优质
            </Tag>
          );
        } else if (text === 'B') {
          return (
            <Tag icon={<MinusCircleOutlined />} color="warning">
              普通
            </Tag>
          );
        } else {
          return (
            <Tag icon={<CloseCircleOutlined />} color="error">
              劣质
            </Tag>
          );
        }
      }
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
      width: 150
    },
    {
      title: '仓库名称',
      dataIndex: 'repoType',
      key: 'repoType',
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_: any, record: any) => (
        <Space>
          <a onClick={() => edit(record)}>编辑</a>
          <Popconfirm
            title="确定删除?"
            okText="确认"
            cancelText="取消"
            onConfirm={() => {
              http
                .delete(`/server/productionSlaughter/delete/${record.id}`)
                .then((res) => {
                  const newData = dataSource.filter(
                    (item: { id: any }) => item.id !== record.id
                  );
                  setdataSource(newData);
                });
            }}
          >
            <a style={{ color: '#ff4d4f' }}>删除</a>
          </Popconfirm>
          <Dropdown overlay={menu(record)}>
            <a
              onClick={(e) => {
                e.preventDefault();
              }}
            >
              ···
            </a>
          </Dropdown>
        </Space>
      ),
      fixed: 'right'
    }
  ];
  const menu = (item: any) => (
    <Menu
      items={[
        {
          key: 0,
          label: (
            <Button
              type="primary"
              onClick={(e) => {
                showDrawer(item);
              }}
            >
              详情
            </Button>
          )
        },

        {
          key: 2,
          label: (
            <Button
              onClick={function () {
                window.print();
              }}
            >
              打印
            </Button>
          )
        }
      ]}
    />
  );
  //详情--抽屉
  const showDrawer = (data: any) => {
    setDrawerVisible(true);
    http.get(`/server/productionSlaughter/get/${data.id}`).then((res) => {
      setDrawerid(res.data);
    });
  };

  const onDraweClose = () => {
    setDrawerVisible(false);
  };
  return (
    <DivWrapper>
      <Buttongroup
        checkIt={() => checkIt()}
        add={() => add()}
      />
      <SearchSelector
        dataSource={(e: any) => setdataSource(e)}
        style={{ float: 'right' }}
      />
      <ConfigProvider locale={zhCN}>
        <Table
          dataSource={dataSource}
          columns={FormColumns}
          scroll={{ x: 1300 }}
          pagination={indexTable.pagination}
          rowKey={(i) => i.id}
          rowSelection={{
            type: selectionType,
            ...rowSelection
          }}
        />
      </ConfigProvider>
      <Drawer
        title="详情"
        placement="right"
        size="large"
        onClose={onDraweClose}
        visible={DrawerVisible}
      >
        <Descriptions
          title={`订单批次：${Drawerid.id}`}
          bordered
          style={{ width: '300px' }}
        >
          <Descriptions.Item label="产品名称">
            {Drawerid.productName}
          </Descriptions.Item>
          <Descriptions.Item label="产品等级">
            {Drawerid.grade}
          </Descriptions.Item>
          <Descriptions.Item label="操作员ID">
            {Drawerid.userId}
          </Descriptions.Item>
        </Descriptions>
      </Drawer>
      <Modal
        title="新增数据"
        visible={addModalVisible}
        onOk={handleAddModalOk}
        onCancel={handleAddModalCancel}
      >
        <NewForm newref={newref}></NewForm>
      </Modal>
    </DivWrapper>
  );
});

export default product;
